<template>
  <div>
    <a-drawer
      title="商机详情"
      width="1100"
      :maskClosable="false"
      :visible="detailData.show"
      direction="rtl"
      @close="handleClose">
        <div slot="title">
          <!-- <i class="el-icon-arrow-left"></i> -->
          <span>商机详情</span>
        </div>
      <el-row style="width:1120px;padding-bottom:280px;height:100%;overflow-y:auto">
        <el-col :span="18">
          <el-form
            :model="parames"
            status-icon
            label-position="left"
            ref="parames"
            label-width="94px"
            class="detailForm"
            v-loading="loading"
          >
            <el-row style="padding: 0 40px">
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="资料" name="info">
                  <a-collapse :defaultActiveKey="activeNames" :bordered="false">
                    <a-collapse-panel class="marginB10" header="基本信息" key="1">
                      <el-col :span="12">
                        <el-form-item label="当前状态:">
                          <span v-if="parames.opportunityStatus">{{parames.opportunityStatus.desc}}</span>
                          <span v-if="parames.invalidReason">(原因：{{parames.invalidReason}})</span>
                        </el-form-item>
                        <el-form-item label="联系人:">
                          <span>{{parames.contacts}}</span>
                        </el-form-item>
                        <el-form-item label="联系方式:">
                          <span>{{parames.mobile}}</span>
                        </el-form-item>
                        <el-form-item label="公司名称:">
                          <span>{{parames.customerName}}</span>
                        </el-form-item>
                        <el-form-item label="商机来源:">
                          <span v-if="parames.opportunitySourceType">{{parames.opportunitySourceType.desc}} - {{parames.opportunitySource}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="24">
                        <el-form-item label="标签:">
                          <div>
                            <el-tag size="small" v-if="parames.importanceLabel">{{parames.importanceLabel.desc}}</el-tag>
                            <el-tag size="small" v-if="parames.urgencyLabel">{{parames.urgencyLabel.desc}}</el-tag>
                            <el-tag size="small" v-for="(item,index) in parames.customLabelList" :key="index">{{item}}</el-tag>
                          </div>
                        </el-form-item>
                      </el-col>
                      <el-col :span="16">
                        <el-form-item label="推荐方案:">
                          <el-button size="small" v-if="parames.thinkTankId" @click="handleViewCase">查看关联方案</el-button>
                        </el-form-item>
                        <el-form-item label="需求概述:">
                            <span>{{parames.opportunityOverview}}</span>
                        </el-form-item>
                        <el-form-item label="负责人:">
                            <span>{{parames.director}}</span>
                        </el-form-item>
                      </el-col>
                    </a-collapse-panel>
                    <a-collapse-panel class="marginB10" header="推荐产品" key="2">
                      <el-col :span="24">
                        <el-table :data="parames.opportunityProductList" style="width: 100%" show-summary :summary-method="getSummaries">
                          <el-table-column prop="productName" label="产品名称" width="180"></el-table-column>
                          <el-table-column prop="count" label="数量"></el-table-column>

                          <el-table-column prop="lowerPriceLimit" label="产品价格">
                            <template slot-scope="scope">
                              <span>{{scope.row.lowerPriceLimit}}-{{scope.row.upperPriceLimit}}</span>
                            </template>
                          </el-table-column>
                          <el-table-column prop="giftCount" label="赠送数量"></el-table-column>
                          <el-table-column prop="unitPrice" label="单价(元)"></el-table-column>
                          <el-table-column prop="discount" label="优惠(元)"></el-table-column>
                          <el-table-column label="小计">
                              <template slot-scope="scope">
                                  <span>{{scope.row.count*scope.row.unitPrice-scope.row.discount}}</span>
                              </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </a-collapse-panel>
                  </a-collapse>
                </el-tab-pane>
                <el-tab-pane label="动态" name="dongtai">
                    <el-col :span="24">
                        <el-row>
                            <el-col :span="24">
                                <el-button :type="dongtaiShow?'primary':'text'" size="mini" round @click="dongtaiShow = true">跟进动态</el-button>
                                <el-button size="mini" :type="!dongtaiShow?'primary':'text'" round @click="dongtaiShow = false">操作历史</el-button>
                            </el-col>
                            <el-col :span="24" style="margin-top:30px" v-show="dongtaiShow">
                                <!-- for循环记录 -->
                                <el-row type="flex" style="margin-bottom: 20px" v-for="(item,index) in trendsList" :key="index">  
                                    <el-col style="width: 40px">
                                        <el-avatar size="small">{{item.name}}</el-avatar>
                                    </el-col>
                                    <el-col :span="20">
                                        <el-row>
                                            <el-col :span="24">
                                                <p style="font-size:13px;color:#646464l">
                                                    <span style="color: #bfbfbf">{{item.createBy}}</span>
                                                    <span>添加了</span>
                                                    <span style="color: #bfbfbf" v-if="item.typeEnum">商机 ‧ {{item.typeEnum.desc}}</span>
                                                    <span style="color: #bfbfbf">{{item.createDate | formatDate2}}</span>
                                                </p>
                                            </el-col>
                                            <el-col :span="24" style="margin-top:10px;">
                                                <p class="genjin-text">{{item.content}}</p>
                                            </el-col>
                                        </el-row>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="24" style="margin-top:30px" v-show="!dongtaiShow">
                                <el-row type="flex" style="margin-bottom: 20px" v-for="(item,index) in origanList" :key="index">  
                                    <el-col style="width: 20px">
                                        <i class="el-icon-edit" style="color:#bfbfbf;font-size:12px;"></i>
                                    </el-col>
                                    <el-col :span="20">
                                        <el-row>
                                            <el-col :span="24">
                                                <p style="font-size:13px;color:#646464l">
                                                    <span style="color: #bfbfbf">{{item.operator}}</span>
                                                    <span v-if="item.operationType">{{item.operationType.desc}}·商机</span>
                                                    <span style="color: #bfbfbf">{{item.createDate | formatDate2}}</span>
                                                </p>
                                            </el-col>
                                            <el-col :span="24" style="margin-top:10px;" v-if="item.operationContent">
                                                <p class="genjin-text2">{{item.operationContent}}</p>
                                            </el-col>
                                        </el-row>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-tab-pane>
              </el-tabs>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="5" style="position: fixed;top:80px;right:-10px;width:240px">
          <div class="form-team-box">
            <div style="margin-bottom: 20px">
              <!-- <el-button
                size="small"
                @click="handleOpenContract"
                icon="el-icon-search"
                style="width:200px;text-align: left;margin-bottom:10px"
              >查看合同</el-button> -->
              <span v-if="parames.opportunityStatus">
                <el-button
                size="small"
                @click="handleOpenContract"
                icon="el-icon-refresh"
                v-if="parames.opportunityStatus.name !== 'INVALID'"
                style="width:200px;text-align: left;margin:0 0 10px "
              >转化为合同</el-button>
              </span>
              
              <el-button
                size="small"
                @click="handleEdit"
                icon="el-icon-edit"
                style="width:200px;text-align: left;margin:0 0 10px 0"
              >编辑商机</el-button>
              <el-popover
                placement="bottom"
                width="200"
                trigger="hover"
                >
                <el-row>
                    <el-col  @click.native="handlePerson">
                        <div class="drp-text">
                            <i class="el-icon-edit"></i>
                            <span>转出</span>
                        </div>
                    </el-col>
                    <el-col @click.native="handleFly">
                        <div class="drp-text">
                            <i class="el-icon-delete"></i>
                            <span>作废商机</span>
                        </div>
                    </el-col>
                    <el-col @click.native="handleYuan">
                        <div class="drp-text" >
                            <i class="el-icon-edit"></i>
                            <span>变更来源</span>
                        </div>
                    </el-col>
                </el-row>
                <el-button size="small"  slot="reference" style="width:200px;text-align: left">
                    <i class="el-icon-menu"></i>
                    <span>更多操作</span>
                    <i style="float: right" class="el-icon-arrow-down"></i>
                </el-button>
              </el-popover>
            </div>
            <p class="formtitle" v-if="parames.userIdList">团队成员（{{parames.userIdList.length}}）人</p>
            <el-row style="margin-top:10px">
                <span v-for="(item,index) in parames.userIdList" :key="index">
                  <el-col style="margin-bottom:10px" v-if="index==0" >
                    <span class="team-icon" style="background: #409efe" v-if="item.userName">{{item.userName.slice(0,1)}}</span>
                    <span class="team-name">{{item.userName}}</span>
                  </el-col>
                  <el-col style="margin-bottom:10px" v-if="index>0" >
                    <span class="team-icon" style="background: #409efe" v-if="item.userName">{{item.userName.slice(0,1)}}</span>
                    <span class="team-name">{{item.userName}}</span>
                    <i class="el-icon-delete team-del" @click="handleDeleteUser(index,item)"></i>
                  </el-col>
                </span>
            </el-row>
            <el-button type="text" style="margin-top:14px" @click="handleAddTeam" icon="el-icon-plus">添加新成员</el-button>
          </div>
        </el-col>
      </el-row>

      <div class="detail-from-bottom-box" :class="{height56: !isFabu, height200:isFabu}">
          <el-row type="flex" v-show="!isFabu">
              <el-col style="width:40px;">
                <el-avatar size="small" icon="el-icon-user-solid" style="margin-top:12px"></el-avatar>
              </el-col>
              <el-col :span="24">
                <el-input type="text" placeholder="添加动态..." size="small" @focus="isFabu = true"></el-input>
              </el-col>
          </el-row>
          <el-row type="flex" v-if="isFabu">
              <el-col style="width:40px;">
                <el-avatar size="small" style="margin-top:12px" icon="el-icon-user-solid"></el-avatar>
              </el-col>
              <el-col :span="24">
                  <el-row>
                      <el-col :span="24">
                        <el-tag style="margin-right:5px;cursor:pointer" size="small" @click="typeEnum = item.name" v-for="(item,index) in trendsTypeData"  :key="index" :type="typeEnum==item.name?'':'info'">{{item.desc}}</el-tag>
                      </el-col>
                      <el-col :span="24">
                          <el-select size="small" v-model="trendsReasonId" placeholder="请选择动态原因" @change="changTrends">
                            <el-option v-for="(item,index) in trendsData" :key="index" :label="item.trendsReasonName" :value="item.id"></el-option>
                        </el-select>
                      </el-col>
                      <el-col :span="24">
                          <el-input v-model="content" type="textarea" placeholder="添加动态..." resize="none"></el-input>
                      </el-col>
                      <el-col :span="18" style="text-align:right">
                          <el-button size="small" type="primary" @click="handleFabu" :loading="floading">发布</el-button>
                            <el-button size="small" @click="isFabu = false">取消</el-button>
                      </el-col>
                  </el-row>
              </el-col>
          </el-row>
      </div>
    </a-drawer>
    <contractDetailDialog :detailData="contractDetailData" @handleOpen="handleOpen"></contractDetailDialog>
    <createdDialog :dialogData="dialogData" @checkOpen="checkOpen"></createdDialog>
    <caseDialog :caseData="caseData" @getThink="getThink"></caseDialog>
    <teamDialog :teamData="teamData" @selectUser="selectUser"></teamDialog>
    <transOrigin :laiyuanData="laiyuanData" @checkRender="checkRender"></transOrigin>
    <transCreated :createdData="createdData" @checkRender="checkRender"></transCreated>
    <invalid :invalidData="invalidData" @checkOpen="checkOpen"></invalid>
    <createdContractDialog :dialogData="hetongdialogData"  @checkOpen="checkOpen"></createdContractDialog>
      

  </div>
</template>

<script>
import caseDialog from './caseDialog'
import contractDetailDialog from "../contractManage/contractDetailDialog.vue"; //合同详情弹窗
import createdDialog from './createdDialog.vue'  //新建商机
import transOrigin from './transOrigin' //更改商机来源
import transCreated from './transCreated' //变更负责人
import invalid from './invalidDialog' //作废原因
import createdContractDialog from "../contractManage/createdContractDialog.vue"; //新建合同

export default {
  props: ["detailData"],
  data() {
    return {
      floading: false,
      loading: false,
      dongtaiShow: true,
      isFabu: false, //是否打开下面的输入跟踪信息
      activeNames: ['1','2'],
      parames: {},
      contractDetailData: { //合同详情弹窗
        origin: '', //跳转来源
        show: false
      },
      teamData: {
        show: false
      },
      laiyuanData: {
        show: false
      },
      hetongdialogData: {
        show: false,
      },
      createdData: {
        show: false
      },
      invalidData: { //作废
        show: false
      },
      dialogData: { //新建弹窗
        type: '',
        id: '',
        show: false,
      },
      caseData: {
        type: '',
        show: false
      },
      typeEnum: '', //动态类型id
      content: '', //动态内容
      trendsData: [], //动态原因下拉值
      trendsReasonId: '', //动态原因
      trendsTypeData: [], //动态类型
      trendsList: [], //动态数据
      activeName: "info",
      origanList: [], //操作轨迹
      tableData: []
    };
  },
  methods: {
    handleClick() {//切换主tab
      if (this.activeName == 'dongtai') {
        this.getTrendsList()
      }
    },
    getTrendsList () {
      this.$post(this.$api.postTrendsOpportunityList,{
          opportunityId: this.detailData.id
        }).then(response => {
          if (response.data.succeed) {
            let data = response.data.data
            data.forEach(el=>{
              el.name = el.createBy.slice(0,1)
            })
            this.trendsList = data
          }
        })
      this.$post(this.$api.postRecordNormalList,{ //操作历史
          projectId: this.detailData.id
        }).then(response => {
          if (response.data.succeed) {
            this.origanList = response.data.data
          }
        })
    },
    changTrends (id) {
      let obj = {}
      obj = this.trendsData.find((item)=>{
        return item.id === id;//筛选出匹配数据
      });
      this.content = obj.trendsReasonName
    },
    handleFabu () { //发布动态内容
      if (!this.content) {
        this.$message.error('请输入动态内容！');
        return false
      }
      this.floading = true
      this.$post(this.$api.postTrendsOpportunityAdd,{
        objectID: this.detailData.id,
        typeEnum: this.typeEnum,
        content: this.content,
        trendsReasonId: this.trendsReasonId
      }).then(response => {
        if (response.data.succeed) {
          this.$message({
            message: '发布成功',
            type: 'success'
          })
          this.content = ''
          this.trendsReasonId = ''
          setTimeout(() => {
            this.floading = false
            this.getTrendsList()
          }, 200);
        }
      })
    },
    handleDeleteUser (index,item) { //删除组内人员
      if (item.teamMemberId) {
        this.$post(this.$api.postOpportunityTeamMemberDel,{
          teamMemberId: item.teamMemberId
        }).then(response => {
          if (response.data.succeed) {
            this.$message({ type:'success',message: '删除成功'})
            this.parames.userIdList.splice(index,1)
          }
        })
      } else {
        this.parames.userIdList.splice(index,1)
      }
    },
    handleViewCase () { //查看推荐方案
      this.caseData.type = 'edit'
      this.caseData.id = this.parames.thinkTankId
      this.caseData.show = true
    },
    handleAddTeam () { //添加新成员
      this.teamData.show = true
    },
    checkRender () {
      this.render()
    },
    selectUser (value) { //添加选择的成员
      let select = value //选中的数组
      let userIdList = []
      let origan = this.parames.userIdList //本身存在的数组
      select.forEach(el=>{
        let i = 0
        origan.forEach((bl,index)=>{
          if (el.userId == bl.userId) {
            i = 1
          }
        })
        if (i !== 1) {
          userIdList.push(el.userId)
        }
      })
      this.$post(this.$api.postOpportunityTeamMemberAdd,{
        teamId:  this.detailData.id,
        userIdList: userIdList
      }).then(response => {
        if (response.data.succeed) {
          this.render()
        }
      })
    },
    getThink () { //保存方案的回调
      
    },
    handleClose() {//关闭弹窗
      this.detailData.show = false;
    },
    checkOpen (type) { //重新打开并向上刷新列表数据
      this.detailData.show = true
      if (type == '1') { //是点击了修改保存按钮-需刷新列表数据
        setTimeout(() => {
          this.$emit('checkRender')
        }, 200);
      } else if (type == '2') { //商机转合同关闭自身
        this.handleClose()
        this.$emit('checkRender')
      }
    },
    handleOpen () { //回退打开本弹窗
      this.detailData.show = true;
    },
    render () {
      this.loading = true
      this.$post(this.$api.postOpportunityFind,{ //根据id获取详情商机数据
        opportunityId: this.detailData.id
      }).then(response => {
        if (response.data.succeed) {
          this.parames = response.data.data
          this.parames.userIdList = response.data.data.teamMemberList
          setTimeout(() => {
            this.loading = false
          }, 200);
        }
      })
      this.$post(this.$api.postTrendsReasonList).then(response => {
        if (response.data.succeed) {
          this.trendsData = response.data.data
        }
      })
    },
    getSummaries(param) { //产品合计
        const { columns, data } = param;
        const sums = [];
        let values = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if (column.property == 'unitPrice') {
            values = data.map(item => Number(item.unitPrice * item.count-item.discount))
          }
          if (index == 6) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '.00';
          } else {
            sums[index] = '';
          }
        });
        return sums;
    },
    handleOpenContract () { //转化为合同
      this.hetongdialogData.show = true;
      this.hetongdialogData.type = 'tranes';
      this.hetongdialogData.title = '新建合同'
      this.hetongdialogData.sjId = this.detailData.id //商机id
      this.handleClose()
    },
    handleEdit () { //修改商机-关闭自身弹窗
      this.dialogData.id = this.detailData.id
      this.dialogData.type = 'edit'
      this.dialogData.title = '编辑商机'
      this.dialogData.show = true
      this.handleClose()
    },
    handleFly () { //修改商机-作废商机
      this.invalidData.type = 'one'
      this.invalidData.id = this.detailData.id
      this.invalidData.show = true
    },
    handlePerson () { //变更商机负责人
      this.createdData.type = 'shangji'
      this.createdData.id = this.detailData.id
      this.createdData.directorId = this.parames.directorId
      this.createdData.show = true
    },
    handleYuan () { //变更来源
      this.laiyuanData.id = this.detailData.id
      this.laiyuanData.opportunitySourceType = this.parames.opportunitySourceType.name
      this.laiyuanData.opportunitySourceId = this.parames.opportunitySourceId
      this.laiyuanData.show = true
    }
  },
  components: {
    contractDetailDialog,
    createdDialog,
    caseDialog,
    transOrigin,
    transCreated,
    invalid,
    createdContractDialog
  },
  computed: { //计算属性
    changeDialog () {
      return this.detailData.show
    }
  },
  watch: {
    changeDialog: {
      handler (curVal, oldVal) {
        if (curVal) {
          this.$utils.getEnumberation('postTrendsTrendsType','trendsTypeData',this) //动态枚举
          this.typeEnum = 'RECORD'
          this.render()
        } else {
          this.activeName = "info"
          this.content = ''
          this.trendsReasonId = ''
        }
      }
    },
    deep: true
  }
};
</script>

<style scoped>
</style>
